<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\AdminUser;
use App\Models\Department;
use App\PatentApply;
use App\Repositories\PatentTransactionRepository;
use App\Services\PatentTransactionService;
use App\Transaction;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Layout\Content;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

class PatentTransactionController extends Controller
{
    use HasResourceActions;

    protected $title = '已转化专利';
    public $repository;
    public $service;

    public function __construct(PatentTransactionRepository $repository, PatentTransactionService $service)
    {
        $this->repository = $repository;
        $this->service = $service;
    }

    public function index(Content $content)
    {
        $grid = $this->grid();
        $grid->header(function (Builder $builder) {
            $year = date('Y');
            $data = Transaction::query()
                ->select(DB::raw('count(*) as count,patent_type_id'))
                ->whereYear('created_at', $year)
                ->groupBy(['patent_type_id'])->get()->map(function ($item) {
                    return [
                        'name'  => data_get(patent_type_select_option(), $item['patent_type_id']),
                        'value' => $item['count']
                    ];
                })->pluck('value', 'name')->toArray();
            $title = $year . '年（总计：' . array_sum($data) . '）';
            return view('admin.statistics.common-table-header', compact('data', 'title'));
        });
        return $content
            ->title($this->title)
            ->body($grid);
    }

    protected function grid()
    {
        $grid = $this->repository->adminGrid();
        $grid = $this->service->gridColumn($grid, 1);
        $grid->actions(function (Actions $actions) {
            $actions->disableView();
            //$actions->disableEdit();
        });
        $grid->disableCreateButton(false);
        return $grid;

    }

    public function create(Content $content): Content
    {
        return $content
            ->title($this->title)
            ->body($this->form());
    }

    public function edit($id, Content $content): Content
    {
        return $content
            ->title($this->title)
            ->body($this->form()->edit($id));
    }

    protected function form()
    {
        $form = $this->repository->form();
        $form->text('patent_sn', '申请号')->required();
        $form->text('patent_name', '专利名称')->required();
        $form->radio('patent_type_id', '专利类型')->options(patent_type_select_option())->required();
        $form->text('buyer', __('受让方'))->required();
        $form->text('amount', __('转化金额（万）'))->required();
        $form->select('type', __('转化类型'))->options(collect(PatentApply::PTM)->map(function ($vo) {
            return ['name' => $vo];
        })->pluck('name', 'name'));
        $form->date('date', __('转化日期'));
        $form->select('department_id', '负责单位')->options(Department::departmentOptions());
        $form->select('user_id', '负责人')->options(AdminUser::userOptions());
        $form->text('contact_person', __('联系人'));
        $form->text('contact_mobile', __('联系电话'));
        $form->saving(function (Form $form) {
            $form->department_id = $form->department_id ?: 0;
            $form->user_id = $form->user_id ?: 0;
            if ($form->amount && !is_numeric($form->amount)) {
                return back()->withInput()->withErrors([
                    'amount' => '请填写有效金额'
                ]);
            }
        });
        return $form;
    }
}
